package org.jeecg.modules.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.config.TenantContext;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.SpringContextUtils;
import org.jeecg.common.util.TokenUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.system.entity.SysUserRole;
import org.jeecg.modules.system.service.ISysPackPermissionService;
import org.jeecg.modules.system.service.ISysPermissionService;
import org.jeecg.modules.system.service.ISysUserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class IdentityService {

    @Autowired
    private ISysUserRoleService sysUserRoleService;
    @Autowired
    private ISysPackPermissionService sysPackPermissionService;
    @Autowired
    private ISysPermissionService sysPermissionService;

    public String getUserId() {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        return sysUser.getId();
    }

    public List<String> getRoleIds() {
        List<SysUserRole> roleList = sysUserRoleService.list(new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getUserId, getUserId()));
        return roleList.stream().map(SysUserRole::getRoleId).collect(Collectors.toList());
    }

    public String getRoleIdByRequest() {
        HttpServletRequest request = SpringContextUtils.getHttpServletRequest();
        //尝试获取加密后的roleId
        String roleIdE = request.getParameter(CommonConstant.X_ROLE_ID);
        if (roleIdE == null) {
            roleIdE = oConvertUtils.getString(request.getHeader(CommonConstant.X_ROLE_ID));
        }
        if (StringUtils.isEmpty(roleIdE)) {
            throw new RuntimeException("未指定roleId！");
        }
        //判断该用户是否有该角色
        for (String roleId : getRoleIds()) {
            if (DigestUtils.md5Hex(roleId).equals(roleIdE)) return roleId;
        }
        throw new RuntimeException("角色不匹配！");
    }

    public String getTenantPackIdByRequest() {
        HttpServletRequest request = SpringContextUtils.getHttpServletRequest();
        //尝试获取加密后的roleId
        String tenantPackId = request.getHeader(CommonConstant.X_TENANT_PACK_ID);
        if (tenantPackId == null) {
            tenantPackId = oConvertUtils.getString(request.getHeader(CommonConstant.X_TENANT_PACK_ID));
        }
        if (StringUtils.isEmpty(tenantPackId)) {
            return null;
        }
        // Todo 该判断会导致出现错误，有产品包不一定有角色
        //判断该用户是否有该角色
        for (String roleId : getRoleIds()) {
            if (DigestUtils.md5Hex(roleId).equals(tenantPackId)) return roleId;
        }
        return tenantPackId;
//        throw new RuntimeException("租户产品包不匹配！");
    }

    public Integer getTenantId() {
        String tenantId = TenantContext.getTenant();
        //如果通过线程获取租户ID为空，则通过当前请求的request获取租户（shiro排除拦截器的请求会获取不到租户ID）
        if (oConvertUtils.isEmpty(tenantId)) {
            try {
                tenantId = TokenUtils.getTenantIdByRequest(SpringContextUtils.getHttpServletRequest());
            } catch (Exception e) {
            }
        }
        if (oConvertUtils.isEmpty(tenantId)) {
            tenantId = "0";
        }
        return Integer.getInteger(tenantId);
    }

}
